// 菜单组件
import React, { useState, createContext } from 'react';
import classNames from 'classnames';
import { IMenuItemProps } from './menuItem';

type MenuMode = 'horizontal' | 'vertical';  // 横向/纵向
type SelectCallback = (selectedindex: string) => void; // 选择回调
// 定义属性
export interface IMenuProps {
    defaultIndex?: string;// 默认索引
    className?: string;
    mode?: MenuMode;
    style?: React.CSSProperties;
    onSelect?: SelectCallback;
    children?: React.ReactNode;
    defaultOpenSubMenus?: string[];
}
interface IMenuContext {
    index: string;
    onSelect?: SelectCallback;
    mode?: MenuMode;
    defaultOpenSubMenus?: string[];
}
export const MenuContext = createContext<IMenuContext>({ index: '0' });
const Menu: React.FC<IMenuProps> = (props) => {
    const { defaultIndex = '0', className, mode = 'horizontal', style, onSelect, defaultOpenSubMenus = [], children } = props;
    const [currentActive, setActive] = useState<string>(defaultIndex); // 当前选择的索引
    const classes = classNames('menu', className, {
        "menu-vertical": mode === 'vertical',
        "menu-horizontal": mode !== 'vertical'
    });
    const handleClick = (index: string) => {
        setActive(index); // 更新状态
        if (onSelect) {
            onSelect(index);
        }
    }
    // 传递给子组件的信息
    const passedContext: IMenuContext = {
        index: currentActive,
        onSelect: handleClick,
        mode,
        defaultOpenSubMenus
    }

    const renderChildren = () => {
        return React.Children.map(children, (child, index) => {
            const childrenElement = child as React.FunctionComponentElement<IMenuItemProps>;
            const { displayName } = childrenElement.type;
            if (displayName === "MenuItem" || displayName === "SubMenu") {
                // 克隆 childrenElement 并传递新的属性index
                return React.cloneElement(childrenElement, { index: index.toString() });
            } else {
                console.log("警告:Menu组件的子组件不是MenuItem!");
            }
        });
    }

    return (
        <ul className={classes} style={style} data-testid="test-menu">
            <MenuContext.Provider value={passedContext}>
                {/* 将context传递给子组件 */}
                {renderChildren()}
            </MenuContext.Provider>
        </ul>
    );
}

export default Menu;